package com.dhcc.DRGsHosp.facade.impl;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.openkoala.koala.commons.InvokeResult;
import org.openkoala.koalacommons.resourceloader.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;

import com.dhcc.DRGsHosp.application.MedicalRecordApplication;
import com.dhcc.DRGsHosp.facade.dto.IndexCalDTO;
import com.dhcc.DRGsHosp.facade.impl.assembler.IndexCalAssembler;
import com.dhcc.DRGsHosp.infra.util.DataSourceUtil;

/**
 * @title		:DataExportImpl.java
 * @description	:
 * @author		:lileizheng
 * @date		:2015年12月30日
 * @version     :1.0
 * @copyright   :DHCC 2013-2014 
 */
public class DataExportImpl {

	@Autowired
	private MedicalRecordFacadeImpl medicalRecordImpl;
	@Autowired
	private MedicalRecordApplication  application;
	
	public void dataExport(){
		IndexCalDTO dto = new IndexCalDTO();
		medicalRecordImpl.dataExport(dto);
	}
	
	public InvokeResult dataExport(IndexCalDTO dto){
		if(!StringUtils.hasLength(dto.getDateFrom()) || !StringUtils.hasLength(dto.getDateTo())){
			Date dNow = new Date();   //当前时间
			Date dBefore = new Date();
			 
			Calendar calendar = Calendar.getInstance(); //得到日历
			calendar.setTime(dNow);//把当前时间赋给日历
			calendar.add(Calendar.DAY_OF_MONTH, -1);  //设置为前一天
			dBefore = calendar.getTime();   //得到前一天的时间

			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); //设置时间格式
			String dateFrom = sdf.format(dBefore);    //格式化前一天
			String dateTo = sdf.format(dNow); //格式化当前时间
			dto.setDateFrom(dateFrom);
			dto.setDateTo(dateTo);
		}
		String dataPath=DataSourceUtil.class.getResource("/").getFile().toString();  
		dataPath = dataPath.substring(1,dataPath.lastIndexOf("WEB-INF"))+"upload/";
		String filename = dto.getDateFrom()+"~"+dto.getDateTo()+".xml";
		try{
			//实例化解析器
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			//创建Document对象
			Document doc = builder.newDocument();
			//创建XML文件所需的各种对象并序列化
			Element root = doc.createElement("CASES");
			
			List<Object[]> resultList = application.findMedicalRecords(IndexCalAssembler.toEntity(dto));
			if(resultList.size()>20000){
				throw new Exception("数据量超过20000, 请缩减区间！");
			}
			for(Object[] objs: resultList){
				Element name = doc.createElement("CASE");
				Element element = doc.createElement("Age");
				Text nameText = doc.createTextNode(objs[0]!=null?objs[0].toString():"");
				element.appendChild(nameText);
				name.appendChild(element);
				element = doc.createElement("Gender");
				nameText = doc.createTextNode(objs[1]!=null?objs[1].toString():"");
				element.appendChild(nameText);
				name.appendChild(element);
				element = doc.createElement("TotalCost");
				nameText = doc.createTextNode(objs[2]!=null?objs[2].toString():"");
				element.appendChild(nameText);
				name.appendChild(element);
				element = doc.createElement("DrugCost");
				nameText = doc.createTextNode(objs[3]!=null?objs[3].toString():"");
				element.appendChild(nameText);
				name.appendChild(element);
				element = doc.createElement("MaterialCost");
				nameText = doc.createTextNode(objs[4]!=null?objs[4].toString():"");
				element.appendChild(nameText);
				name.appendChild(element);
				element = doc.createElement("InDays");
				nameText = doc.createTextNode(objs[5]!=null?objs[5].toString():"");
				element.appendChild(nameText);
				name.appendChild(element);
				element = doc.createElement("OutDate");
				nameText = doc.createTextNode(objs[6]!=null?objs[6].toString():"");
				element.appendChild(nameText);
				name.appendChild(element);
				element = doc.createElement("OutWay");
				nameText = doc.createTextNode(objs[7]!=null?objs[7].toString():"");
				element.appendChild(nameText);
				name.appendChild(element);
				element = doc.createElement("NewbornAge");
				nameText = doc.createTextNode(objs[8]!=null?objs[8].toString():"");
				element.appendChild(nameText);
				name.appendChild(element);
				element = doc.createElement("NewbornWeight");
				nameText = doc.createTextNode(objs[9]!=null?objs[9].toString():"");
				element.appendChild(nameText);
				name.appendChild(element);
				element = doc.createElement("VentilatorTime");
				nameText = doc.createTextNode(objs[10]!=null?objs[10].toString():"");
				element.appendChild(nameText);
				name.appendChild(element);
				element = doc.createElement("DRGCode");
				nameText = doc.createTextNode(objs[11]!=null?objs[11].toString():"");
				element.appendChild(nameText);
				name.appendChild(element);
				
				String parid = objs[12]!=null?objs[12].toString():"";
				//五大类费用
				List<Object[]> drgFeeList = application.findDRGsFeeBy(parid);
				if(drgFeeList.size()>0){
					Object[] drgFeeObj = drgFeeList.get(0);
					Element drgFee = doc.createElement("DRGFee");
					element = doc.createElement("Treatment");
					nameText = doc.createTextNode(drgFeeObj[1]!=null?drgFeeObj[1].toString():"");
					element.appendChild(nameText);
					drgFee.appendChild(element);
					element = doc.createElement("Inspecting");
					nameText = doc.createTextNode(drgFeeObj[0]!=null?drgFeeObj[0].toString():"");
					element.appendChild(nameText);
					drgFee.appendChild(element);
					element = doc.createElement("Nursing");
					nameText = doc.createTextNode(drgFeeObj[2]!=null?drgFeeObj[2].toString():"");
					element.appendChild(nameText);
					drgFee.appendChild(element);
					element = doc.createElement("Management");
					nameText = doc.createTextNode(drgFeeObj[3]!=null?drgFeeObj[3].toString():"");
					element.appendChild(nameText);
					drgFee.appendChild(element);
					element = doc.createElement("DrugMaterial");
					nameText = doc.createTextNode(drgFeeObj[4]!=null?drgFeeObj[4].toString():"");
					element.appendChild(nameText);
					drgFee.appendChild(element);
					name.appendChild(drgFee);
				}
				
				//诊断
				List<Object[]> diagList = application.findDiagnosisBy(parid);
				if(diagList.size()>0){
					for(Object[] diagObjs: diagList){
						Element diags = doc.createElement("Diags");
						element = doc.createElement("DiagCode");
						nameText = doc.createTextNode(diagObjs[2]!=null?diagObjs[2].toString():"");
						element.appendChild(nameText);
						diags.appendChild(element);
						element = doc.createElement("DiagDesc");
						nameText = doc.createTextNode(diagObjs[3]!=null?diagObjs[3].toString():"");
						element.appendChild(nameText);
						diags.appendChild(element);
						element = doc.createElement("DiagType");
						nameText = doc.createTextNode(diagObjs[1]!=null?diagObjs[1].toString():"");
						element.appendChild(nameText);
						diags.appendChild(element);
						name.appendChild(diags);
					}
				}
				
				//手术
				List<Object[]> operList = application.findOperationBy(parid);
				if(operList.size()>0){
					for(Object[] operObjs: operList){
						Element opers = doc.createElement("Opers");
						element = doc.createElement("OperCode");
						nameText = doc.createTextNode(operObjs[1]!=null?operObjs[1].toString():"");
						element.appendChild(nameText);
						opers.appendChild(element);
						element = doc.createElement("OperDesc");
						nameText = doc.createTextNode(operObjs[2]!=null?operObjs[2].toString():"");
						element.appendChild(nameText);
						opers.appendChild(element);
						element = doc.createElement("OperType");
						nameText = doc.createTextNode(operObjs[3]!=null?operObjs[3].toString():"");
						element.appendChild(nameText);
						opers.appendChild(element);
						element = doc.createElement("OperLevel");
						nameText = doc.createTextNode(operObjs[4]!=null?operObjs[4].toString():"");
						element.appendChild(nameText);
						opers.appendChild(element);
						name.appendChild(opers);
					}
				}
				
				root.appendChild(name);
			}
			doc.appendChild(root);
			TransformerFactory tFactory = TransformerFactory.newInstance();
			Transformer transformer = tFactory.newTransformer();
			/** 编码 */
			transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
			DOMSource source = new DOMSource(doc);
			File upload = new File(dataPath);
			if(!upload.exists() && !upload.isDirectory()){
				upload.mkdir();
			}
			File file =new File(dataPath+filename);
			StreamResult result = new StreamResult(file);
			transformer.transform(source, result);
		}catch(Exception e){
			return InvokeResult.failure(e.getMessage());
		}
		System.out.println("导出文件位置:"+dataPath+filename);
		return InvokeResult.success(dataPath+filename);
	}
}
